<?php

namespace App\Http\Services;

use App\Http\Model\ComeBack;
use App\Http\Model\FinanceDiamond;
use App\Http\Model\FinanceJd;
use App\Http\Model\FinanceRechargeOrder;
use App\Http\Model\Gift;
use App\Http\Model\GiftBag;
use App\Http\Model\GiftLibrary;
use Exception;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\Hint;
use App\Http\Model\LuckDraw;
use App\Http\Model\Mall;
use App\Http\Model\User;
use App\Modules\LuckDraw\Models\UserPropModel;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class ComeBackServices extends CommonServices
{
    protected $comeBackModel;//活动配置模型
    protected $userModel;
    protected $jd_model;
    protected $diamond_model;
    protected $mall_model;
    protected $giftBag;
    protected $giftLiblary;
    protected $luck_draw_user_prop_model;
    protected $financeRechargeOrder;

    protected $success_log = 'come_back.log';
    protected $error_log = 'error_come_back.log';

    protected $popSiginListUser = 'COME:BACK:POP:SIGINLIST:USER:';//当日用户弹出签到列表  string COME:BACK:POP:SIGINLIST:USER:{user_id}=>{int}
    protected $comeBackRecharge = 'COME:BACK:MISSION:RECHARGE:DAY:USER:';//每日充值用户任务 string 
    protected $comeBackRechargeAll = 'COME:BACK:MISSION:RECHARGE:ALL:USER:';//累计充值用户任务 string 
    protected $comeBackJdDayRedis = 'COME:BACK:MISSION:JD:DY:USER:';//用户每日消耗金豆数
    protected $comeBackJdAllRedis = 'COME:BACK:MISSION:JD:ALL:USER:';//用户累计消耗金豆

    public function __construct()
    {
        parent::__construct();
        $this->comeBackModel = new ComeBack();
        $this->userModel = new User();
        $this->jd_model = new FinanceJd();
        $this->diamond_model = new FinanceDiamond();
        $this->mall_model = new Mall();
        $this->giftBag = new GiftBag();
        $this->giftLiblary = new Gift();
        $this->luck_draw_user_prop_model = new UserPropModel();
        $this->financeRechargeOrder = new FinanceRechargeOrder();
    }

    //后台-新增配置项
    public function addComeBackConfig($resquest){
        $code = Hint::SUCCESS;
        $data = [];
        $msg = 'ok';
        do{
            if(empty($resquest['name'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动名称必填";
                break;
            }
            if(empty($resquest['icon'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动图片必传";
                break;
            }
            if(empty($resquest['start_time'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动开始时间必传";
                break;
            }
            if(empty($resquest['end_time'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动结束时间必传";
                break;
            }
            if(empty($resquest['type'])){
                $code = Hint::PARAM_ERROR;
                $msg = "上传文件类型必传";
                break;
            }
            if(empty($resquest['days'])){
                $code = Hint::PARAM_ERROR;
                $msg = "持续天数必传";
                break;
            }
            if(empty($resquest['ids'])){
                $code = Hint::PARAM_ERROR;
                $msg = "上传文件内容为空";
                break;
            }

            //时间转换
            $start_time = Carbon::parse($resquest['start_time'])->startOfDay()->toDateTimeString();
            $end_time = Carbon::parse($resquest['end_time'])->endOfDay()->toDateTimeString();
            //入库
            DB::beginTransaction();
            try{
                $data = [
                    'ac_name' => $resquest['name'],
                    'icon' => $resquest['icon'],
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'type' => $resquest['type'],
                    'days' => $resquest['days'],
                    'execl_url' => $resquest['execl_url'],
                    'created_at' => Carbon::now()->toDateTimeString()
                ];
                if($resquest['type'] == 1){
                    $data['user_ids'] = $resquest['ids'];
                }elseif($resquest['type'] == 2){
                    $data['phones'] = $resquest['ids'];
                }
                $this->comeBackModel->addComeBackConfig($data);
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                write_log($this->error_log,'ERROR 新增配置失败',['msg'=>$e->getMessage(),'line'=>$e->getLine(),'data'=>$resquest]);
                $code = Hint::ERR_DB_FAIL;
                $msg = '入库失败,错误信息:'.$e->getMessage();
                break;
            };
        }while(false);
        return compact('code','data','msg');
    }

    //后台-编辑配置项
    public function editComeBackConfig($resquest){
        $code = Hint::SUCCESS;
        $data = [];
        $msg = 'ok';
        do{
            if(empty($resquest['id'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动id必填";
                break;
            }
            if(empty($resquest['name'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动名称必填";
                break;
            }
            if(empty($resquest['icon'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动图片必传";
                break;
            }
            if(empty($resquest['start_time'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动开始时间必传";
                break;
            }
            if(empty($resquest['end_time'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动结束时间必传";
                break;
            }
            if(empty($resquest['type'])){
                $code = Hint::PARAM_ERROR;
                $msg = "上传文件类型必传";
                break;
            }
            if(empty($resquest['days'])){
                $code = Hint::PARAM_ERROR;
                $msg = "持续天数必传";
                break;
            }
            if(empty($resquest['ids'])){
                $code = Hint::PARAM_ERROR;
                $msg = "上传文件内容为空";
                break;
            }
            //时间转换
            $start_time = Carbon::parse($resquest['start_time'])->startOfDay()->toDateTimeString();
            $end_time = Carbon::parse($resquest['end_time'])->endOfDay()->toDateTimeString();
            //入库
            DB::beginTransaction();
            try{
                $data = [
                    'ac_name' => $resquest['name'],
                    'icon' => $resquest['icon'],
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'type' => $resquest['type'],
                    'days' => $resquest['days'],
                    'execl_url' => $resquest['execl_url'],
                    'updated_at' => Carbon::now()->toDateTimeString()
                ];
                if($resquest['type'] == 1){
                    $data['user_ids'] = $resquest['ids'];
                }elseif($resquest['type'] == 2){
                    $data['phones'] = $resquest['ids'];
                }
                $this->comeBackModel->editComeBackConfig($resquest['id'],$data);
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                write_log($this->error_log,'ERROR 修改配置失败',['msg'=>$e->getMessage(),'line'=>$e->getLine(),'data'=>$resquest]);
                $code = Hint::ERR_DB_FAIL;
                $msg = '入库失败,错误信息:'.$e->getMessage();
                break;
            };
        }while(false);
        return compact('code','data','msg');
    }

    //删除配置
    public function delComeBackConfig($resquest){
        $code = Hint::SUCCESS;
        $data = [];
        $msg = 'ok';
        do{
            if(empty($resquest['id'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动id必填";
                break;
            }
            //入库
            DB::beginTransaction();
            try{
                $data = [
                    'is_delete' => 1,
                    'updated_at' =>  Carbon::now()->toDateTimeString()
                ];
                $this->comeBackModel->editComeBackConfig($resquest['id'],$data);
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                write_log($this->error_log,'ERROR 删除配置失败',['msg'=>$e->getMessage(),'line'=>$e->getLine(),'data'=>$resquest]);
                $code = Hint::ERR_DB_FAIL;
                $msg = '入库失败,错误信息:'.$e->getMessage();
                break;
            }
        }while(false);
        return compact('code','data','msg');
    }

    //添加-签到配置
    public function addSiginConfig($resquest){
        $code = Hint::SUCCESS;
        $data = [];
        $msg = 'ok';
        do{
            if(empty($resquest['act_id'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动id必填";
                break;
            }
            if(empty($resquest['day'])){
                $code = Hint::PARAM_ERROR;
                $msg = "天数必填";
                break;
            }
            if(empty($resquest['send_type'])){
                $code = Hint::PARAM_ERROR;
                $msg = "赠送类型必填";
                break;
            }
            if(empty($resquest['send_num'])){
                $code = Hint::PARAM_ERROR;
                $msg = "数量必填";
                break;
            }
            if(empty($resquest['goods_id']) && in_array($resquest['send_type'],[3,4])){
                $code = Hint::PARAM_ERROR;
                $msg = "商品id必填";
                break;
            }
            if(empty($resquest['img'])){
                $code = Hint::PARAM_ERROR;
                $msg = "图片必填";
                break;
            }
            if(empty($resquest['award_name'])){
                $code = Hint::PARAM_ERROR;
                $msg = "签到名称必填";
                break;
            }
            try{
                DB::beginTransaction();
                $data = [
                    'act_id' => $resquest['act_id'],
                    'day' => $resquest['day'],
                    'send_type' => $resquest['send_type'],
                    'goods_id' => isset($resquest['goods_id']) ? $resquest['goods_id'] : 0,
                    'send_num' => $resquest['send_num'],
                    'img' => $resquest['img'],
                    'award_name' => $resquest['award_name'],
                    'created_at' => Carbon::now()->toDateTimeString(),
                ];
                $this->comeBackModel->insertSiginCongfig($data);
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                write_log($this->error_log,'ERROR 新增签到配置失败',['msg'=>$e->getMessage(),'line'=>$e->getLine(),'data'=>$resquest]);
                $code = Hint::ERR_DB_FAIL;
                $msg = '入库失败,错误信息:'.$e->getMessage();
                break;
            }
        }while(false);
        return compact('code','data','msg');
    }

    //编辑签到配置
    public function editSiginConfig($resquest){
        $code = Hint::SUCCESS;
        $data = [];
        $msg = 'ok';
        do{
            if(empty($resquest['sigin_id'])){
                $code = Hint::PARAM_ERROR;
                $msg = "签到配置id必填";
                break;
            }
            if(empty($resquest['day'])){
                $code = Hint::PARAM_ERROR;
                $msg = "天数必填";
                break;
            }
            if(empty($resquest['send_type'])){
                $code = Hint::PARAM_ERROR;
                $msg = "赠送类型必填";
                break;
            }
            if(empty($resquest['send_num'])){
                $code = Hint::PARAM_ERROR;
                $msg = "数量必填";
                break;
            }
            if(empty($resquest['goods_id']) && in_array($resquest['send_type'],[3,4])){
                $code = Hint::PARAM_ERROR;
                $msg = "商品id必填";
                break;
            }
            if(empty($resquest['img'])){
                $code = Hint::PARAM_ERROR;
                $msg = "图片必填";
                break;
            }
            if(empty($resquest['award_name'])){
                $code = Hint::PARAM_ERROR;
                $msg = "签到名称必填";
                break;
            }
            try{
                DB::beginTransaction();
                $data = [
                    'day' => $resquest['day'],
                    'send_type' => $resquest['send_type'],
                    'goods_id' => isset($resquest['goods_id']) ? $resquest['goods_id'] : 0,
                    'send_num' => $resquest['send_num'],
                    'img' => $resquest['img'],
                    'award_name' => $resquest['award_name'],
                    'updated_at' => Carbon::now()->toDateTimeString(),
                ];
                $this->comeBackModel->editSiginCongfig($resquest['sigin_id'],$data);
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                write_log($this->error_log,'ERROR 新增签到配置失败',['msg'=>$e->getMessage(),'line'=>$e->getLine(),'data'=>$resquest]);
                $code = Hint::ERR_DB_FAIL;
                $msg = '入库失败,错误信息:'.$e->getMessage();
                break;
            }
        }while(false);
        return compact('code','data','msg');
    }

    //删除签到配置
    public function delSiginConfig($param){
        $code = Hint::SUCCESS;
        $data = [];
        $msg = 'ok';
        do{
            if(empty($param['sigin_id'])){
                $code = Hint::PARAM_ERROR;
                $msg = "签到id必填";
                break;
            }
            //入库
            DB::beginTransaction();
            try{
                $data = [
                    'is_delete' => 1,
                    'updated_at' =>  Carbon::now()->toDateTimeString()
                ];
                $this->comeBackModel->editSiginCongfig($param['sigin_id'],$data);
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                write_log($this->error_log,'ERROR 删除配置失败',['msg'=>$e->getMessage(),'line'=>$e->getLine(),'data'=>$param]);
                $code = Hint::ERR_DB_FAIL;
                $msg = '入库失败,错误信息:'.$e->getMessage();
                break;
            }
        }while(false);
        return compact('code','data','msg');
    }

    //添加每日任务
    public function addDayTask($resquest){
        $code = Hint::SUCCESS;
        $data = [];
        $msg = 'ok';
        do{
            if(empty($resquest['act_id'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动id必填";
                break;
            }
            if(empty($resquest['type'])){
                $code = Hint::PARAM_ERROR;
                $msg = "任务类型必填";
                break;
            }
            if(empty($resquest['need_value'])){
                $code = Hint::PARAM_ERROR;
                $msg = "任务门槛必填";
                break;
            }
            if(empty($resquest['award_type'])){
                $code = Hint::PARAM_ERROR;
                $msg = "奖励类型必填";
                break;
            }
            if(empty($resquest['award_num'])){
                $code = Hint::PARAM_ERROR;
                $msg = "奖励类型必填";
                break;
            }
            if(in_array($resquest['award_type'],[3,4])){
                if(empty($resquest['award_id'])){
                    $code = Hint::PARAM_ERROR;
                    $msg = "奖励id必填";
                    break;
                }
            }
            //入库
            DB::beginTransaction();
            try{
                $data = [
                    'act_id' => $resquest['act_id'],
                    'desc' => $resquest['desc'],
                    'type' => $resquest['type'],
                    'need_value'=> $resquest['need_value'],
                    'award_type'=> $resquest['award_type'],
                    'award_name'=> $resquest['award_name'],
                    'award_num'=> $resquest['award_num'],
                    'award_id'=> $resquest['award_id'],
                    'is_day' => $resquest['is_day'],
                    'created_at' =>  Carbon::now()->toDateTimeString()
                ];
                $this->comeBackModel->addTask($data);
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                write_log($this->error_log,'ERROR 新增每日配置失败',['msg'=>$e->getMessage(),'line'=>$e->getLine(),'data'=>$data]);
                $code = Hint::ERR_DB_FAIL;
                $msg = '入库失败,错误信息:'.$e->getMessage();
                break;
            }
        }while(false);
        return compact('code','data','msg');
    }

    //编辑每日任务
    public function editDayTask($resquest){
        $code = Hint::SUCCESS;
        $data = [];
        $msg = 'ok';
        do{
            if(empty($resquest['task_id'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动id必填";
                break;
            }
            if(empty($resquest['type'])){
                $code = Hint::PARAM_ERROR;
                $msg = "任务类型必填";
                break;
            }
            if(empty($resquest['need_value'])){
                $code = Hint::PARAM_ERROR;
                $msg = "任务门槛必填";
                break;
            }
            if(empty($resquest['award_type'])){
                $code = Hint::PARAM_ERROR;
                $msg = "奖励类型必填";
                break;
            }
            if(empty($resquest['award_num'])){
                $code = Hint::PARAM_ERROR;
                $msg = "奖励类型必填";
                break;
            }
            if(in_array($resquest['award_type'],[3,4])){
                if(empty($resquest['award_id'])){
                    $code = Hint::PARAM_ERROR;
                    $msg = "奖励id必填";
                    break;
                }
            }
            //入库
            DB::beginTransaction();
            try{
                $data = [
                    'desc' => $resquest['desc'],
                    'type' => $resquest['type'],
                    'need_value'=> $resquest['need_value'],
                    'award_type'=> $resquest['award_type'],
                    'award_name'=> $resquest['award_name'],
                    'award_num'=> $resquest['award_num'],
                    'award_id'=> $resquest['award_id'],
                    'is_day' => $resquest['is_day'],
                    'updated_at' =>  Carbon::now()->toDateTimeString()
                ];
                $this->comeBackModel->editTask($resquest['task_id'],$data);
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                write_log($this->error_log,'ERROR 新增每日配置失败',['msg'=>$e->getMessage(),'line'=>$e->getLine(),'data'=>$data]);
                $code = Hint::ERR_DB_FAIL;
                $msg = '入库失败,错误信息:'.$e->getMessage();
                break;
            }
        }while(false);
        return compact('code','data','msg');
    }

    //删除每日任务配置
    public function delTaskConfig($resquest){
        $code = Hint::SUCCESS;
        $data = [];
        $msg = 'ok';
        do{
            if(empty($resquest['task_id'])){
                $code = Hint::PARAM_ERROR;
                $msg = "活动id必填";
                break;
            }
            //入库
            DB::beginTransaction();
            try{
                $data = [
                    'is_delete' => 1,
                    'updated_at' =>  Carbon::now()->toDateTimeString()
                ];
                $this->comeBackModel->editTask($resquest['task_id'],$data);
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                write_log($this->error_log,'ERROR 删除配置失败',['msg'=>$e->getMessage(),'line'=>$e->getLine(),'data'=>$data]);
                $code = Hint::ERR_DB_FAIL;
                $msg = '入库失败,错误信息:'.$e->getMessage();
                break;
            }
        }while(false);
        return compact('code','data','msg');
    }

    //前台获取悬浮图片显示条件
    public function getFloatIcon($userId){
        $code = Hint::SUCCESS;
        $msg = 'ok';
        $data = [
            'icon' => '',
            'expire_time' => 0,
            'is_start' => 0,
            'today_sign' => 0,
            'act_id' => 0,
            'signList' => [],
            'is_show_dialog' => 0,
        ];
        do{
            //查询配置项是否包含此用户id
            $configInfo = $this->comeBackModel->getComeBackConfig();
            //判断用户是否在数据里
            if(empty($configInfo)){
               $code = Hint::ERR_NORMAL;
               $msg = '配置未加载';
               break;
            }
            //判断活动是否开启
            if(strtotime($configInfo['start_time']) > time()){
                $code = Hint::ERR_NORMAL;
                $msg = '活动未开始';
                break;
            }

            //获取名单中的用户
            $arr = [];
            $userInfo = $this->userModel->get_user($userId);
            if($configInfo['type'] == 1){//用户id
                $arr = explode(',',$configInfo['user_ids']);
            }elseif($configInfo['type'] == 2){//手机号
                $userMobileInfo = $this->comeBackModel->getUserPhone($userId);
                $userId = $userMobileInfo['mobile_phone'];
                $arr = explode(',',$configInfo['phones']);
            }
            if(!in_array($userId,$arr)){
                $code = Hint::ERR_NORMAL;
                $msg = '非配置用户';
                break;
            }

            $end_time = strtotime($configInfo['end_time']);
            //查看用户是否签到,若签到了则按照签到时间+配置结束天数作为结束时间
            $checkUserSiginStatus = $this->comeBackModel->checkUserSigin($userInfo['user_id'],1);
            if(!empty($checkUserSiginStatus)){
                $end_time = Carbon::parse($checkUserSiginStatus['last_time'])->endOfDay()->addDays($configInfo['days']-1)->timestamp;
                $is_start = 1;
            }
            //判断结束时间
            if($end_time < time()){
                $code = Hint::ERR_NORMAL;
                $msg = '活动已结束';
                break;
            }
            //获取签到列表
            $signList = $this->comeBackModel->getSiginList($configInfo['id']);
            if(empty($signList)){
                $code = Hint::ERR_NORMAL;
                $msg = '签到未配置';
                break;
            }
            //获取对应签到天数下用户是否进行签到
            $siginArr = [];
            //获取用户今日是否签到
            $todaySigin = $this->comeBackModel->chekTodaySigin($userInfo['user_id']);
            foreach($signList as $k=>$v){
                $siginArr[$k]['act_id'] = $configInfo['id'];
                $siginArr[$k]['sign_id'] = $v['sigin_id'];
                $siginArr[$k]['pic'] = build_image($v['img']);
                $siginArr[$k]['send_id'] = $v['goods_id'];
                //查寻用户是否签到过
                $checkSigin = $this->comeBackModel->checkUserSigin($userInfo['user_id'], $v['day'], $v['sigin_id']);
                $siginArr[$k]['is_sign'] = 0;
                if(!empty($checkSigin)){
                    $siginArr[$k]['is_sign'] = 1;
                }
                $siginArr[$k]['send_name'] = $v['award_name'];
                $siginArr[$k]['send_num'] = $v['send_num'];
                $siginArr[$k]['sign_day'] = '第'.$v['day'].'天';
            }

            if(Redis::get($this->popSiginListUser.$userInfo['user_id'])){
                $code = Hint::ERR_NORMAL;
                $msg = '当日已弹出';
                $data['icon'] = build_image($configInfo['icon']);
                $data['act_id'] = $configInfo['id'];
                $data['is_start'] = $is_start;
                $data['expire_time'] = !empty($checkUserSiginStatus) ? $end_time - time() : strtotime($configInfo['end_time']) - time();
                $data['today_sign'] = $todaySigin;
                $data['is_show_dialog'] = 0;
                $data['signList'] = $siginArr;
                
                break;
            }
            
            //获取悬浮icon
            $data = [
                'icon' => build_image($configInfo['icon']),
                'act_id' => $configInfo['id'],
                'is_start' => $is_start,
                'expire_time' => !empty($checkUserSiginStatus) ? $end_time - time() : strtotime($configInfo['end_time']) - time(),
                'signList' => $siginArr,
                'today_sign' => $todaySigin,
                'is_show_dialog' => 1,
            ];
            $endDay = Carbon::today()->endOfDay()->toDateTimeString();
            $expireTime = Carbon::parse($endDay)->diffInSeconds(date('Y-m-d H:i:s',time()));
            Redis::SET($this->popSiginListUser.$userInfo['user_id'],1);
            Redis::EXPIRE($this->popSiginListUser.$userInfo['user_id'],$expireTime);
        }while(false);
        return compact('code','data','msg');
    }

    //进行签到处理
    public function doSigin($userId, $siginId, $actId){
        do{
            $code = Hint::SUCCESS;
            $msg = 'ok';
            $data = [];
            //查询今日是否已签到
            $todaySigin = $this->comeBackModel->chekTodaySigin($userId);
            if($todaySigin){
                $code = Hint::PARAM_ERROR;
                $msg = '今日已签到';
                break;
            }
            //进行签到处理
            $siginInfo = $this->comeBackModel->getSiginInfo($siginId, $actId);
            if(empty($siginInfo)){
                $code = Hint::PARAM_ERROR;
                $msg = '签到失败';
                break;
            }
            $doSigin = $this->comeBackModel->doSigin($userId,$siginInfo);
            if(!$doSigin){
                $code = Hint::PARAM_ERROR;
                $msg = '请重新尝试';
                break;
            }
            //查看签到是否有送礼操作
            if($siginInfo['send_type'] == 1){
                //送金豆
                $config = config('pay');
                $jd_desc = $config['wallet_change_desc']['jd_come_back_incr'];
                $this->jd_model->inc($userId, $doSigin, 15 , $siginInfo['send_num'], $jd_desc);
                $msg = '签到成功,获得'.$siginInfo['send_num'].'个金豆~';
            }elseif($siginInfo['send_type'] == 2){
                //送钻石
                $config = config('pay');
                $diamond_desc = $config['wallet_change_desc']['diamond_come_back_incr'];
                $this->diamond_model->inc($userId, 11, 0, 82, $siginInfo['send_num'] ,$diamond_desc);
                $msg = '签到成功,获得'.$siginInfo['send_num'].'个钻石~';
            }elseif($siginInfo['send_type'] == 3){
                //商品信息
                $goodInfo = $this->mall_model->getMallGoodByGoodsId($siginInfo['goods_id']);
                if(empty($goodInfo)){
                    $code = Hint::PARAM_ERROR;
                    $msg = '商品下发失败';
                    break;
                }
                $skuList = $this->mall_model->getSkuDataByGoods($siginInfo['goods_id']);
                if(empty($skuList[0])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '商品不存在';
                    break;
                }
                $goodId = $siginInfo['goods_id'];
                $goodMap[$goodId]['goods_name'] = $goodInfo['goods_name'];
                $goodMap[$goodId]['goods_type'] = $goodInfo['goods_type'];
                $goodMap[$goodId]['sku_id'] = $skuList[0]['sku_id'];
                //赠送商品(头像框/气泡)
                $timeLimit = $siginInfo['send_num']*86400;
                $ret_data = $this->mall_model->shoppingAct(
                    11,
                    $userId,
                    $siginInfo['goods_id'],
                    $goodMap[$goodId]['goods_name'],
                    $goodMap[$goodId]['goods_type'],
                    $goodMap[$goodId]['sku_id'],
                    $timeLimit,
                    0,
                    $timeLimit,
                    time(),
                    2
                );
                $msg = '签到成功,获得'.$goodInfo['goods_name'].'*'.$siginInfo['send_num'].'天,已为您自动下发到我的装扮~';
            }elseif($siginInfo['send_type'] == 4){
                //送礼物
                $giftInfo = $this->giftLiblary->get_gift($siginInfo['goods_id']);
                $res = $this->giftBag->inc((int)$userId, 0, (int)$siginInfo['goods_id'], (int)$siginInfo['send_num'], 3001);
                $msg = '签到成功,获得'.$giftInfo['name'].'*'.$siginInfo['send_num'].'个,已为您自动下发到我的背包~';
            }elseif($siginInfo['send_type'] == 5){
                //送告白币
                $res = $this->luck_draw_user_prop_model->add(1000,$userId,$siginInfo['send_num']);
                $msg = '签到成功,获得告白币'.'*'.$siginInfo['send_num'].'个,已为您自动下发';
            }
            $configInfo = $this->comeBackModel->getComeBackConfig();
            $checkUserSiginStatus = $this->comeBackModel->checkUserSigin($userId,1);
            if(!empty($checkUserSiginStatus)){
                $end_time = Carbon::parse($checkUserSiginStatus['last_time'])->endOfDay()->addDays($configInfo['days']-1)->timestamp;
            }
            $data['msg'] = $msg;
            $data['expire_time'] = $end_time - time();
        }while(false);
        return compact('code','data','msg');
    }

    //获取每日任务列表
    public function getMissionList($userId, $actId){
        do{
            $code = Hint::SUCCESS;
            $msg = 'ok';
            $data = [];
            //获取对应活动下的每日任务
            $dayMission = $this->comeBackModel->dayMission($actId);
            //获取对应活动下的累计任务
            $allMission = $this->comeBackModel->mission($actId);
            //获取活动名称
            $actInfo = $this->comeBackModel->getComeBackConfig();
            $dayTask = [];
            $allTask = [];
            foreach($dayMission as $k=> $v){
                //查看对应用户是否完成任务情况
                $checkUserMission = $this->comeBackModel->checkUserMission($userId, $v['task_id'], 1);
                $dayTask[$k]['task_id'] = $v['task_id'];
                $dayTask[$k]['task_name'] = $v['desc'];
                $dayTask[$k]['task_status'] = !empty($checkUserMission) ? $checkUserMission['status'] : 0;
            }
            foreach($allMission as $key=> $val){
                //查看对应用户是否完成任务情况
                $checkUserAllMission = $this->comeBackModel->checkUserMission($userId, $val['task_id'], 0);
                $allTask[$key]['task_id'] = $val['task_id'];
                $allTask[$key]['task_name'] = $val['desc'];
                $allTask[$key]['task_status'] = !empty($checkUserAllMission) ? $checkUserAllMission['status'] : 0;
            }
            $data = [
                'top_title_img' => build_image($actInfo['banner']),
                'dayTask' => $dayTask,
                'allTask' => $allTask,
            ];
        }while(false);
        return compact('code','data','msg');
    }

    //领取活动奖励
    public function getAward($userId, $taskId){
        do{
            $code = Hint::SUCCESS;
            $msg = 'ok';
            $data = [];
            //查看任务是否存在
            $taskInfo = $this->comeBackModel->getMissionInfo($taskId);
            if(empty($taskInfo)){
                $code = Hint::ERR_NORMAL;
                $msg = '任务不存在';
                break;
            }
            //结束时间
            $configInfo = $this->comeBackModel->getComeBackConfig();
            $checkUserSiginStatus = $this->comeBackModel->checkUserSigin($userId,1);
            $end_time = strtotime($configInfo['end_time']);
            if(!empty($checkUserSiginStatus)){
                $end_time = Carbon::parse($checkUserSiginStatus['last_time'])->endOfDay()->addDays($configInfo['days']-1)->timestamp;
            }
            if($end_time < time()){
                $code = Hint::ERR_NORMAL;
                $msg = '活动已过期';
                break;
            }
            //查看用户是否完成任务
            $userMissionInfo = $this->comeBackModel->checkUserMission($userId, $taskId, $taskInfo['is_day']);
            if(empty($userMissionInfo)){
                $code = Hint::ERR_NORMAL;
                $msg = '暂未完成任务';
                break;
            }
            if(!redis_lock('get_mission_award',5)){
                $code = Hint::ERR_NORMAL;
                $msg = '请勿重复点击';
                break;
            }
            //更新数据
            $updata = [
                'status' => 2,//1=已完成未领取 2=已领取
                'is_day' => $taskInfo['is_day'],
                'type' => $taskInfo['type'],
                'award_id' => $taskInfo['award_id'],
                'award_type' => $taskInfo['award_type'],//奖励类型1=钻石 2=金豆 3=商品 4=礼物 5=告白币
                'award_num' => $taskInfo['award_num'],//奖励数量
                'updated_at' => Carbon::now()->toDateTimeString(),
            ];
            $status = $this->comeBackModel->updateStreamLog($userMissionInfo['stream_id'],$updata);
            if($status){
                //发放对应奖励
                $returnMsg = $this->sendMissionAward($userId,$taskInfo,$userMissionInfo['stream_id']);
            }
            $data['msg'] = $returnMsg;
        }while(false);
        return compact('code','data','msg');
    }

    //奖励发放
    public function sendMissionAward($userId, $taskInfo, $dataId){
        if($taskInfo['award_type'] == 2){ //发钻石
             //送钻石
             $config = config('pay');
             $diamond_desc = $config['wallet_change_desc']['diamond_come_back_incr'];
             $this->diamond_model->inc($userId, 11, 0, 82, $taskInfo['award_num'] ,$diamond_desc);
             $msg = '恭喜获得'.$taskInfo['award_num'].'个钻石~';
        }elseif($taskInfo['award_type'] == 1){//发金豆
            $config = config('pay');
            $jd_desc = $config['wallet_change_desc']['jd_come_back_incr'];
            $this->jd_model->inc($userId, $dataId, 15 , $taskInfo['award_num'], $jd_desc);
            $msg = '恭喜获得'.$taskInfo['award_num'].'个金豆~';
        }elseif($taskInfo['award_type'] == 3){//发商品
            //商品信息
            $goodInfo = $this->mall_model->getMallGoodByGoodsId($taskInfo['award_id']);
            $skuList = $this->mall_model->getSkuDataByGoods($taskInfo['award_id']);
            $goodId = $taskInfo['award_id'];
            $goodMap[$goodId]['goods_name'] = $goodInfo['goods_name'];
            $goodMap[$goodId]['goods_type'] = $goodInfo['goods_type'];
            $goodMap[$goodId]['sku_id'] = $skuList[0]['sku_id'];
            //赠送商品(头像框/气泡)
            $timeLimit = $taskInfo['award_num']*86400;
            $ret_data = $this->mall_model->shoppingAct(
                11,
                $userId,
                $taskInfo['award_id'],
                $goodMap[$goodId]['goods_name'],
                $goodMap[$goodId]['goods_type'],
                $goodMap[$goodId]['sku_id'],
                $timeLimit,
                0,
                $timeLimit,
                time(),
                2
            );
            $msg = '恭喜获得'.$goodInfo['goods_name'].'*'.$taskInfo['award_num'].'天,已为您自动下发到我的装扮~';
        }elseif($taskInfo['award_type'] == 4){//送礼物
            //送礼物
            $giftInfo = $this->giftLiblary->get_gift($taskInfo['award_id']);
            $res = $this->giftBag->inc((int)$userId, 0, (int)$taskInfo['award_id'], (int)$taskInfo['award_num'], 3001);
            $msg = '恭喜获得'.$giftInfo['name'].'*'.$taskInfo['award_num'].'个,已为您自动下发到我的背包~';
        }elseif($taskInfo['award_type'] == 5){
            //送告白币
            $res = $this->luck_draw_user_prop_model->add(1000,$userId,$taskInfo['award_num']);
            $msg = '恭喜获得告白币'.'*'.$taskInfo['award_num'].'个,已为您自动下发';
        } 
        return $msg;
    }

    /**
     * 任务完成记录
     *
     * @param [type] $userId
     * @param [type] $type 任务类型1=充值2=金豆消耗3=礼物送礼消耗钻石4=房间时长
     * @return void
     */
    public function comeBackeMissionStream($userId,$type){
        try{
            //查询任务信息
            $configInfo = $this->comeBackModel->getComeBackConfig();
            if(empty($configInfo)){
                return true;
            }
            //开始时间
            if(strtotime($configInfo['start_time']) > time()){
                return true;
            }
            //结束时间判断
            $checkUserSiginStatus = $this->comeBackModel->checkUserSigin($userId,1);
            //用户未签到则不进行入库
            if(empty($checkUserSiginStatus)){ 
                return true;
            }
            $end_time = strtotime($configInfo['end_time']);
            if(!empty($checkUserSiginStatus)){
                $end_time = Carbon::parse($checkUserSiginStatus['last_time'])->endOfDay()->addDays($configInfo['days']-1)->timestamp;
            }
            if($end_time < time()){
                return true;
            }
            
            if($type == 1){//充值
                $checkDay = Redis::get($this->comeBackRecharge.$userId);
                //查询对应充值每日任务
                $getMissionInfo = $this->comeBackModel->getMissionInfoByActId($configInfo['id'], 1, 1);
                if(empty($getMissionInfo)){
                    return true;
                }

                if(empty($checkDay)){
                    //查询用户当天充值总数
                    $start_time = Carbon::today()->startOfDay()->timestamp;
                    $day_end_time = Carbon::today()->endOfDay()->timestamp;
                    $dayCount = $this->comeBackModel->getUserPayDiamond($userId, $start_time, $day_end_time);
                    //每日
                    $this->doInsertStream($userId, $dayCount, $getMissionInfo['need_value'], $getMissionInfo['task_id'], 1, $type);
                    $diffTime = (new Carbon)->diffInSeconds(date('Y-m-d H:i:s',$day_end_time));
                    if($dayCount >= $getMissionInfo['need_value']){
                        Redis::SET($this->comeBackRecharge.$userId,1);
                        Redis::EXPIRE($this->comeBackRecharge.$userId,$diffTime);
                    }
                    
                }
                
                $checkAll = Redis::get($this->comeBackRechargeAll.$userId);
                if(empty($checkAll)){
                    //查询累计充值任务
                    $allMissionInfo = $this->comeBackModel->getMissionInfoByActId($configInfo['id'], 1, 0);
                    if(empty($allMissionInfo)){
                        return true;
                    }
                    //查询用户累计充值总数
                    $start_time = Carbon::parse($checkUserSiginStatus['last_time'])->startOfDay()->timestamp;
                    $end_time = $end_time;
                    $allCount = $this->comeBackModel->getUserPayDiamond($userId, $start_time, $end_time);
                    //累计
                    $this->doInsertStream($userId, $allCount, $allMissionInfo['need_value'], $allMissionInfo['task_id'], 0, $type);
                    $diffTime = (new Carbon)->diffInSeconds(date('Y-m-d H:i:s',$end_time));
                    if($allCount >= $allMissionInfo['need_value']){
                        Redis::SET($this->comeBackRechargeAll.$userId,1);
                        Redis::EXPIRE($this->comeBackRechargeAll.$userId,$diffTime);
                    }
                
                }
                return true;
            }elseif($type == 2){//金豆消耗
                //查询每日任务明细
                $getMissionInfo = $this->comeBackModel->getMissionInfoByActId($configInfo['id'], 2, 1);
                if(empty($getMissionInfo)){
                    return true;
                }

                $checkDayJd = Redis::get($this->comeBackJdDayRedis.$userId);
                if(empty($checkDayJd)){
                    //查询用户当天消耗金豆总数
                    $start_time = Carbon::today()->startOfDay()->toDateTimeString();
                    $day_end_time = Carbon::today()->endOfDay()->toDateTimeString();
                    $dayCostJd = $this->comeBackModel->getUserCostJd($userId, $start_time, $day_end_time);
                    //每日
                    $this->doInsertStream($userId, $dayCostJd, $getMissionInfo['need_value'], $getMissionInfo['task_id'], 1, $type);
                    $diffTime = (new Carbon)->diffInSeconds($day_end_time);
                    if($dayCostJd >= $getMissionInfo['need_value']){
                        Redis::SET($this->comeBackJdDayRedis.$userId,1);
                        Redis::EXPIRE($this->comeBackJdDayRedis.$userId,$diffTime);
                    }
                    
                } 

                $checkAllJd = Redis::get($this->comeBackJdAllRedis.$userId);
                if(empty($checkAllJd)){
                    //查询累计消耗金豆任务
                    $allMissionInfo = $this->comeBackModel->getMissionInfoByActId($configInfo['id'], 2, 0);
                    if(empty($allMissionInfo)){
                        return true;
                    }
                    //查询用户累计消耗金豆总数
                    $start_time = Carbon::parse($checkUserSiginStatus['last_time'])->startOfDay()->toDateTimeString();
                    $end_time = $end_time;
                    $allCount = $this->comeBackModel->getUserCostJd($userId, $start_time, date('Y-m-d H:i:s',$end_time));
                    //累计
                    $this->doInsertStream($userId, $allCount, $allMissionInfo['need_value'], $allMissionInfo['task_id'], 0, $type);
                    $diffTime = (new Carbon)->diffInSeconds(date('Y-m-d H:i:s',$end_time));
                    if($allCount >= $allMissionInfo['need_value']){
                        Redis::SET($this->comeBackJdAllRedis.$userId,1);
                        Redis::EXPIRE($this->comeBackJdAllRedis.$userId,$diffTime);
                    }
                    
                }     
            }
            return true;
        }catch(\Exception $e){
            write_log($this->error_log,'ERROR ',['msg'=>$e->getMessage(),'line'=>$e->getLine(),'file'=>$e->getFile()]);
            return true;
        }
        
    }

    /**
     * 处理任务
     *
     * @param [type] $userId 用户id
     * @param [type] $count 实际数量
     * @param [type] $needCount 门槛数量
     * @param [type] $taskId 任务id
     * @param [type] $is_day 1=每日任务 0=累计任务
     * @param [type] $type  任务类型1=充值2=金豆消耗3=礼物送礼消耗钻石4=房间时长
     * @return void
     */
    public function doInsertStream($userId, $count, $needCount, $taskId, $is_day, $type){
        if($count >= $needCount){
            $data = [
                'user_id' => $userId,
                'task_id' => $taskId,
                'status' => 1,
                'is_day' => $is_day,
                'type' => $type,
                'created_at' => Carbon::now()->toDateTimeString()
            ];
            $this->comeBackModel->insertStream($data);
        }
    }
}